<?php

namespace app\api\controller;

use app\common\controller\Frontend;
use ba\PayLib;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use Yansongda\Pay\Pay;

class PayApi extends Frontend
{

    protected array $noNeedPermission = ['*'];
    protected array $noNeedLogin=['*'];

    /**
     * @param string $order_sn 订单号
     * @param string $subject 商品名称
     * @param string $module 模块  orderPay 下单  recharge 充值  add_clock_service 加钟服务
     * @return void
     */
    public function submit (): void
    {
        $post = $this->request->post();
//
        $out_trade_no = $post['order_sn']; #平台订单号
//        $subject = $post['subject']; #商品名称
//        $module = $post['module']; #模块
//
//        switch ($module) {
//            case 'orderPay':
//                $amount = $this->orderPayReturnPrice($out_trade_no);
//                break;
//            case 'recharge':
//                $amount = $post['amount'];
//                break;
//            case 'add_clock_service':
//                $amount = $post['amount'];
//                break;
//            default:
//                $this->error('模块错误');
//        }
//
//        $amount = intval(bcmul($amount, 100));
//
//        $attach = [
//            'module' => $module
//        ];
//
//        $order = [
//            'out_trade_no' => $out_trade_no,
//            'description'  => $subject,
//            'amount'       => [
//                'total' => $amount,
//            ],
//            'attach'       => json_encode($attach)   #扩展信息
//        ];
//
        $order = [
            'out_trade_no' => $out_trade_no,
            'description'  => "测试",
            'amount'       => [
                'total' => (int)100,
            ],
            'payer'        => [
                'openid' => $this->openid(),
            ],
            'attach'       => 'orderPay'   #扩展信息
        ];
        $result = Pay::wechat(PayLib::getConfig())->mp($order);
        $this->success('支付成功', [
            'order_sn' => $out_trade_no,
            'pay_url'  => $result,
        ]);
    }


    /**
     * 查询订单支付金额
     * @param $order_sn
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function orderPayReturnPrice ($order_sn): mixed
    {
        $orderInfo = \app\api\model\Order::where('order_sn', $order_sn)
            ->where('user_id', $this->auth->id)
            ->find();
        if (!$orderInfo) {
            $this->error('订单不存在');
        }

        #返回订单实际支付费用
        return $orderInfo->service_reality_price;
    }
}